//必须带done回调 执行完成调用
import { ElMessage } from 'element-plus'
import trim from 'lodash/trim'
import cloneDeep from 'lodash/cloneDeep'
import { translateTitle } from '@/utils/i18n'

export default function arithmeticOperation({ vm, action, done, callbackData }) {
  // console.log('vm', vm)
  const arithmeticList = cloneDeep(action.extension.arithmeticList.value)

  arithmeticList.forEach((item) => {
    // 对获取到的消息内容做变量拆分 -- #{}符号包裹内容视为变量
    const staticList = item.valueExpression.split(/#{.*?}/gi)
    const variableList = item.valueExpression.match(/#{(.+?)\}/g)
    if (variableList && variableList.length) {
      // 如果有配置变量 则先获取变量值
      variableList.forEach((variableItem, index) => {
        let variableContent = ''
        variableItem = trim(variableItem.slice(2, -1))
        if (variableItem.indexOf('->') !== -1) {
          const fieldList = variableItem.split('->')
          variableContent = callbackData
          fieldList.forEach((fieldItem) => {
            // 如果没有后续值则不继续往下取值
            if (variableContent[trim(fieldItem)] === undefined) return
            variableContent = variableContent[trim(fieldItem)]
          })
        } else {
          variableContent = callbackData[variableItem]
        }
        staticList.splice(index * 2 + 1, 0, variableContent)
      })
      item.valueExpression = staticList.join('')
    }
    console.log('算式 ----------- ', item.valueExpression)
    try {
      // 执行字符串
      item.valueExpression = Function('"use strict";return (' + item.valueExpression + ')')()
    } catch (error) {
      console.log('error', error)
      ElMessage({
        showClose: true,
        message: translateTitle('Ve.eventTask.算数运算'),
        type: 'error',
      })
      item.valueExpression = 0
    }
  })
  let callbackObj = {}
  arithmeticList.forEach((item) => {
    callbackObj[item.keyField] = item.valueExpression
  })
  // 存储动作数据
  vm.$store.dispatch('actionDatas/setActionsData', {
    moduleId: vm.info._id,
    actionId: action._id,
    actionData: callbackObj,
  })
  done(null, callbackObj)
}
